#pragma once

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cerrno>
#include <string>
#include <functional>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>

#include "sock.hpp"
#include "log.hpp"
#include "err.h"

namespace select_ns
{
    const static int defaultport = 8080;
    const static int fdnum = sizeof(fd_set) * 8;
    const static int defaultfd = -1;

    typedef std::function<std::string(std::string)> func_t;

    class selectServer
    {
    public:
        selectServer(const func_t &func, const uint16_t &port = defaultport)
            : _port(port), _func(func), _listensock(-1), _fdarray(nullptr)
        {
        }

        void initServer()
        {
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);

            _fdarray = new int[fdnum];

            for (int i = 0; i < fdnum; i++)
                _fdarray[i] = defaultfd;
            _fdarray[0] = _listensock;
        }
        void Print()
        {
            std::cout << "fd list: ";
            for (int i = 0; i < fdnum; i++)
            {
                if (_fdarray[i] != defaultfd)
                {
                    std::cout << _fdarray[i] << " ";
                }
            }
        }
        void Accepter(int listensock)
        {
            std::string clientip;
            uint16_t clientport;
            int sock = Sock::Accept(listensock, &clientip, &clientport);

            if (sock < 0)
                return;
            LogMessage(NORMAL, "accept success[%s:%d]", clientip.c_str(), clientport);

            // sock我们能直接recv/read 吗？不能，整个代码，只有select有资格检测事件是否就绪
            // 将新的sock 托管给select！
            // 将新的sock托管给select的本质，其实就是将sock，添加到fdarray数组中即可！
            int i = 0;
            for (; i < fdnum; i++)
            {
                if (_fdarray[i] == defaultfd)
                    continue;
                else
                    break;
            }
            if (i == fdnum)
            {
                LogMessage(WARNING, "server is full,please wait");
                close(sock);
            }
            else
                _fdarray[i] = sock;
            Print();
        }
        void Recver(int sock, int pos)
        {
            // 1. 读取request
            char buffer[1024];
            ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                LogMessage(NORMAL, "client#: %s", buffer);
            }
            else if (s == 0)
            {
                close(sock);
                _fdarray[pos] = defaultfd;
                LogMessage(NORMAL, "client quit");
                return;
            }
            else
            {
                close(sock);
                _fdarray[pos] = defaultfd;
                LogMessage(ERROR, "client error:%s", strerror(errno));
                return;
            }

            // 2. 处理request
            std::string response = _func(buffer);

            // 3. 返回response
            write(sock, response.c_str(), response.size());
        }

        void HandlerEvent(fd_set &rfds)
        {
            for (int i = 0; i < fdnum; i++)
            {
                if (_fdarray[i] == defaultfd)
                    continue;

                if (FD_ISSET(_fdarray[i], &rfds) && _fdarray[i] == _listensock)
                    Accepter(_listensock);
                else if (FD_ISSET(_fdarray[i], &rfds))
                    Recver(_fdarray[i], i);
                else
                {
                }
            }
        }

        void start()
        {
            for (;;)
            {
                fd_set rfds;
                FD_ZERO(&rfds);
                int maxfd = _fdarray[0];

                for (int i = 0; i < fdnum; i++)
                {
                    if (_fdarray[i] == defaultfd)
                        continue;
                    FD_SET(_fdarray[i], &rfds); // 合法 fd 全部添加到读文件描述符集中

                    if (maxfd < _fdarray[i])
                        maxfd = _fdarray[i]; // 更新所有fd中最大的fd
                }

                int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
                switch (n)
                {
                case 0:
                    LogMessage(NORMAL, "timeout...");
                    break;
                case -1:
                    LogMessage(WARNING, "select error,code: %d, err string: %s", errno, strerror(errno));
                    break;
                default:
                    // 说明有事件就绪了,目前只有一个监听事件就绪了
                    LogMessage(NORMAL, "have event ready!");
                    HandlerEvent(rfds);
                    break;
                }
            }
        }
        ~selectServer()
        {
            if (_listensock > 0)
                close(_listensock);
            if (_fdarray)
                delete[] _fdarray;
        }

    private:
        int _port;
        int _listensock;
        int *_fdarray;
        func_t _func;
    };
}